<template>
  <div class="app-container">
    <v-row :gutter="20">
      <v-col>
        <v-form ref="queryForm" v-show="showSearch" label-width="68px">
          <v-row>
            <v-col md="3" style="padding-bottom: 2px;max-width: 250px">
              <v-text-field
                label="任务名称"
                v-model="queryParams.jobName"
                placeholder="请输入任务名称"
                outlined
                dense
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 250px;"
              ></v-text-field>
            </v-col>
            <v-col md="3" style="padding-bottom: 2px;max-width: 150px">
              <v-select
                label="任务组名"
                v-model="queryParams.jobGroup"
                :items="jobGroupOptions"
                item-text="dictLabel"
                item-value="dictValue"
                placeholder="请选择任务组名"
                dense
                outlined
                clearable
                style="width: 200px;"
              ></v-select>
            </v-col>
            <v-col md="2" style="padding-bottom: 2px;max-width: 150px">
              <v-select
                label="任务状态"
                v-model="queryParams.status"
                :items="statusOptions"
                item-text="dictLabel"
                item-value="dictValue"
                placeholder="请选择任务状态"
                dense
                outlined
                clearable
                style="width: 150px;"
              ></v-select>
            </v-col>

            <!-- 按钮区-->
            <v-col cols="12"
                   sm="6"
                   md="2" style="padding-bottom: 0;margin-left: 1rem;height: 40px;margin-top: 8px">
              <p style="display: inline-block;position: absolute">
                <v-btn
                  small color="primary"
                  :loading="loading"
                  @click="handleQuery">
                  <v-icon left>
                    mdi-magnify
                  </v-icon>
                  搜索
                </v-btn>
                <v-btn
                  small
                  :loading="loading"
                  @click="resetQuery"
                  style="margin-left: 10px"
                >
                  <v-icon left>
                    mdi-autorenew
                  </v-icon>
                  重置
                </v-btn>
              </p>
            </v-col>
          </v-row>
        </v-form>

        <!-- 表格操作按钮区 -->
        <v-row style="margin-bottom: -5px">
          <v-col md="1" style="max-width: 84px">
            <v-btn
              color="primary"
              plain
              small
              outlined
              @click="handleAdd"
              v-hasPermi="['monitor:job:add']">
              <v-icon left>
                mdi-plus
              </v-icon>
              新增
            </v-btn>
          </v-col>
          <v-col md="1" style="max-width: 84px">
            <v-btn
              small
              plain
              outlined
              :disabled="single"
              @click="handleUpdate(ids[0])"
              v-hasPermi="['monitor:job:edit']">
              <v-icon left>
                mdi-pencil
              </v-icon>
              修改
            </v-btn>
          </v-col>
          <!--todo 二次确认删除按钮 -->
          <v-col md="1" style="max-width: 84px">
            <span v-if="!showConfirmDelete">
              <v-btn
                small color="error"
                plain
                outlined
                :disabled="multiple"
                @click="onClickDelete"
                v-hasPermi="['monitor:job:remove']">
                <v-icon left>
                  mdi-delete
                </v-icon>
                删除
              </v-btn>
            </span>
            <span v-else>
              <v-tooltip top style="z-index: 1000">
                <template v-slot:activator="{ on, attrs }">
                  <v-btn
                    small color="error"
                    plain
                    outlined
                    :disabled="multiple"
                    v-bind="attrs"
                    v-on="on"
                    @click="handleDelete()"
                    v-hasPermi="['monitor:job:remove']">
                    <v-icon left>
                      mdi-delete
                    </v-icon>
                    确定
                  </v-btn>
                </template>
                <span>请再次点击确定删除</span>
              </v-tooltip>
            </span>
          </v-col>
          <v-col md="1" style="max-width: 84px">
            <v-btn
              small
              plain
              outlined
              @click="handleExport"
              v-hasPermi="['monitor:job:export']">
              <v-icon left>
                mdi-upload
              </v-icon>
              导出
            </v-btn>
          </v-col>
          <v-col md="1" style="max-width: 84px">
            <v-btn
              type="text"
              small
              plain
              outlined
              @click="handleJobLog"
              v-hasPermi="['monitor:job:query']">
              <v-icon left>
                mdi-tune
              </v-icon>
              日志
            </v-btn>
          </v-col>
          <v-col style="float: right">
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </v-col>
        </v-row>
      </v-col>
    </v-row>

    <!-- 表格 -->
    <v-main>
      <v-data-table v-if="jobList"
                    v-model="ids"
                    :headers="headers"
                    :items="jobList"
                    :items-per-page="queryParams.pageSize"
                    hide-default-footer
                    :loading="loading"
                    loading-text="加载中,请稍后.."
                    show-select
                    item-key="jobId"
                    class="elevation-1"
                    no-data-text="暂无数据"
      >

        <template v-slot:item.invokeTarget="{ item }">
          <v-tooltip top>
            <template v-slot:activator="{ on, attrs }">
              <div class="omitted" v-bind="attrs" v-on="on">{{ item.invokeTarget }}</div>
            </template>
            <span>{{ item.invokeTarget }}</span>
          </v-tooltip>
        </template>

        <template v-slot:item.status="{ item }">
          <v-chip
            class="ma-2"
            small
            :color="getColor(item.status)"
            dark
            @click="handleStatusChange(item)"
          >

            <!-- 暂停的 -->
            <v-icon left v-if="item.status == 1">
              mdi-pause-octagon
            </v-icon>

            <!-- 启动的 -->
            <v-icon left v-if="item.status == 0">
              mdi-play
            </v-icon>
            {{ statusFormat(item) }}
          </v-chip>
        </template>

        <!-- 按钮插槽 -->
        <template v-slot:item.actions="{ item }">
          <span v-if="item && !item.showConfirmRun">
            <v-btn color="primary"
                   small
                   plain
                   height="20"
                   width="40"
                   v-hasPermi="['monitor:job:changeStatus']"
                   @click="clickHandleRun(item)">
              <v-icon small>
                mdi-play
              </v-icon>
              执行一次
            </v-btn>
          </span>
          <span v-else>
            <v-tooltip top>
              <template v-slot:activator="{ on, attrs }">
                <v-btn color="primary"
                  small
                  plain
                  height="20"
                  width="40"
                  v-bind="attrs"
                  v-on="on"
                  @click="handleRun(item)"
                  v-hasPermi="['monitor:job:changeStatus']">
                  <v-icon small>
                    mdi-play
                  </v-icon>
                  确定
                </v-btn>
              </template>
              <span>点击确定执行一次任务</span>
            </v-tooltip>
          </span>
          <v-btn text
                 small
                 plain
                 height="20"
                 width="40"
                 @click="handleView(item)"
                 v-hasPermi="['monitor:job:query']" style="margin-left: 13px">
            <v-icon small>
              mdi-eye
            </v-icon>
            详细
          </v-btn>
        </template>
      </v-data-table>
      <!-- 外部分页-->
      <div class="d-flex align-center justify-end text-center">
        <div class="d-flex" style="margin-top: 3px;font-size: 14px;font-weight: 400">
          <span>每页</span>
          <v-select
            v-model="queryParams.pageSize"
            :items="numbers"
            dense
            @change="getList" style="max-width: 80px;max-height: 20px;margin-top: -4px;text-align: center;">
            <template v-slot:selection="{ item, index }">
                  <span style="width: 100%">
                    {{item}}
                  </span>
            </template>
          </v-select>
          <span>条记录</span>
        </div>
        <v-pagination
          v-model="queryParams.pageNum"
          @input="getList"
          :length="queryParams.totalPages"
          :total-visible="7"
        ></v-pagination>
      </div>
    </v-main>

    <!-- 编辑对话框 -->
    <v-dialog
      v-model="visible"
      persistent
      max-width="700px">
      <v-card>
        <!-- 对话框标题 -->
        <v-card-title>
          <span style="font-size: 18px">{{ title }}</span>
        </v-card-title>

        <!-- 表单 -->
        <v-form ref="form" v-model="valid">
          <v-card-text>
            <v-container>
              <v-row>
                <v-col cols="12" sm="6">
                  <v-text-field
                    v-model="form.jobName"
                    :rules="rules.jobName"
                    label="*任务名称"
                    placeholder="请输入任务名称"
                    required
                    clearable
                    dense
                    autofocus
                  ></v-text-field>
                </v-col>
                <v-col cols="12" sm="4">
                  <v-select
                    label="任务分组"
                    v-model="form.jobGroup"
                    :items="jobGroupOptions"
                    item-text="dictLabel"
                    item-value="dictValue"
                    placeholder="请选择"
                    dense
                  ></v-select>
                </v-col>
                <v-col cols="12" sm="12">
                  <v-text-field
                    label="*调用方法"
                    v-model="form.invokeTarget"
                    :rules="rules.invokeTarget"
                    placeholder="请输入调用目标字符串"
                    required
                    clearable
                    dense
                  >
                    <template v-slot:append-outer>
                      <v-tooltip
                        bottom
                      >
                        <template v-slot:activator="{ on }">
                          <v-icon v-on="on">
                            mdi-help-circle-outline
                          </v-icon>
                        </template>
                        Bean调用示例：ryTask.ryParams('ry')
                        <br />Class类调用示例：com.ruoyi.quartz.task.RyTask.ryParams('ry')
                        <br />参数说明：支持字符串，布尔类型，长整型，浮点型，整型
                      </v-tooltip>
                    </template>
                  </v-text-field>
                </v-col>
                <v-col cols="12" sm="6">
                  <v-text-field
                    v-model="form.cronExpression"
                    :rules="rules.cronExpression"
                    label="*cron表达式"
                    placeholder="请输入cron执行表达式"
                    required
                    clearable
                    dense
                  ></v-text-field>
                </v-col>
                <v-col cols="12" sm="6">
                  <v-card-title style="margin: 0;padding-top: 6px;padding-bottom: 0;padding-left: 0">
                    <span class="column-label">是否并发</span>
                  </v-card-title>
                  <v-chip-group
                    mandatory
                    active-class="deep-purple--text text--accent-4"
                    style="margin-top: -35px;margin-left: 85px;"
                  >
                    <v-chip
                      label
                      key="0"
                      @click="form.concurrent = 0"
                    >
                     允许
                    </v-chip>
                    <v-chip
                      label
                      key="1"
                      @click="form.concurrent = 1"
                    >
                      禁止
                    </v-chip>
                  </v-chip-group>
                </v-col>
                <v-col cols="12" sm="12">
                  <v-card-title style="margin: 0;padding-top: 6px;padding-bottom: 0;padding-left: 0;width: 85px">
                    <span class="column-label">错误策略</span>
                  </v-card-title>
                  <v-btn-toggle
                    v-model="form.misfirePolicy"
                    borderless
                    style="margin-top: -28px;margin-left: 85px;display: inline-block;position: absolute"
                  >
                    <v-btn value="1"
                           color="primary" small style="padding: 16px 10px">
                      立即执行
                    </v-btn>
                    <v-btn value="2"
                           color="primary" small style="padding: 16px 10px">
                      执行一次
                    </v-btn>
                    <v-btn value="3"
                           color="primary" small style="padding: 16px 10px">
                      放弃执行
                    </v-btn>
                  </v-btn-toggle>
                </v-col>
                <v-col cols="12" sm="6">
                  <v-radio-group
                    label="状态"
                    v-model="form.status"
                    row dense style="margin: 0;"
                  >
                    <v-radio
                      v-for="dict in statusOptions"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"
                    ></v-radio>
                  </v-radio-group>
                </v-col>
              </v-row>
            </v-container>
            <small class="ml10">*表示必需字段</small>
          </v-card-text>
        </v-form>

        <!-- 底部操作按钮 -->
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            text
            @click="updateVisible(false)">
            取消
          </v-btn>
          <v-btn
            color="blue darken-1"
            text
            @click="submitForm">
            保存
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 任务日志详细 -->
    <v-dialog
      v-model="openView" max-width="700px" persistent>
      <v-card>
        <v-card-title>
          <span style="font-size: 16px;padding: 0;">任务详细</span>
        </v-card-title>
        <v-row :gutter="24" justify="center" style="margin: 0 auto;">
          <v-col>
            <v-card style="width: 98%;margin: 0 auto">
              <v-row>
                <v-col md="6">
                  <v-card-text style="padding: 10px">
                    任务编号： {{ form.jobId }}
                  </v-card-text>
                  <v-card-text style="padding: 10px">
                    任务名称： {{ form.jobName }}
                  </v-card-text>
                  <v-card-text style="padding: 10px">
                    cron表达式： {{ form.cronExpression }}
                  </v-card-text>
                </v-col>
                <v-col md="6">
                  <v-card-text style="padding: 10px">
                    任务分组： {{ jobGroupFormat(form) }}
                  </v-card-text>
                  <v-card-text style="padding: 10px">
                    创建时间： {{ form.createTime }}
                  </v-card-text>
                  <v-card-text style="padding: 10px">
                    下次执行时间： {{ parseTime(form.nextValidTime) }}
                  </v-card-text>
                </v-col>
                <v-col md="12" style="padding-top: 0;padding-bottom: 0">
                  <v-card-text style="padding: 0 10px">
                    调用目标方法： {{ form.invokeTarget }}
                  </v-card-text>
                </v-col>
                <v-col md="6">
                  <v-card-text style="padding: 10px">
                    任务状态： {{ statusFormat(form) }}
                  </v-card-text>
                  <v-card-text style="padding: 10px">
                    执行策略：
                    <span v-if="form.misfirePolicy == 0">默认策略</span>
                    <span v-else-if="form.misfirePolicy == 1">立即执行</span>
                    <span v-else-if="form.misfirePolicy == 2">执行一次</span>
                    <span v-else-if="form.misfirePolicy == 3">放弃执行</span>
                  </v-card-text>
                </v-col>
                <v-col md="6">
                  <v-card-text style="padding: 10px">
                    是否并发： {{ form.concurrent == 0 ? '允许' : '禁止' }}
                  </v-card-text>
                </v-col>
              </v-row>
            </v-card>
          </v-col>
        </v-row>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            text
            @click="openView = false">
            关闭
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
import { listJob, getJob, delJob, addJob, updateJob, runJob, changeJobStatus } from "@/api/monitor/job";

export default {
  name: "Job",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 定时任务表格数据
      jobList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      visible: false,
      // 是否显示详细弹出层
      openView: false,
      // 任务组名字典
      jobGroupOptions: [],
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        totalPages: 0, // 总页数
        jobName: undefined,
        jobGroup: undefined,
        status: undefined
      },
      showConfirmDelete: false,
      // 表单参数
      form: {},
      valid: false,
      numbers: [10, 15, 20, 50, 100], // 每页条数选择
      // v-table 表格头
      headers: [
        { text: '任务编号', value: 'jobId',  align: 'center', sortable: false, width: '85px' },
        { text: '任务名称', value: 'jobName', align: 'center', sortable: false, },
        { text: '任务组名', value: 'jobGroup', align: 'center', sortable: false, },
        { text: '调用目标字符串', value: 'invokeTarget', sortable: false, align: 'center', width: '160px' },
        { text: 'cron执行表达式', value: 'cronExpression', sortable: false, align: 'center' },
        { text: '状态', value: 'status', sortable: false, align: 'center' },
        { text: '操作', value: 'actions', sortable: false, align: 'center' },
      ],
      // 表单校验
      rules: {
        jobName: [
          val => (val || '').length > 0 || '任务名称不能为空'
        ],
        invokeTarget: [
          val => (val || '').length > 0 || '调用目标字符串不能为空'
        ],
        cronExpression: [
          val => (val || '').length > 0 || 'cron执行表达式不能为空'
        ]
      }
    };
  },
  watch: {
    ids() {
      this.handleSelectionChange();
    }
  },
  created() {
    this.getList();
    this.getDicts("sys_job_group").then(response => {
      this.jobGroupOptions = response.data;
    });
    this.getDicts("sys_job_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询定时任务列表 */
    getList() {
      this.ids = [];
      this.loading = true;
      listJob(this.queryParams).then(response => {
        this.jobList = response.rows;
        this.total = response.total;
        // 总页数
        this.queryParams.totalPages = Math.ceil(this.total / this.queryParams.pageSize);
        this.loading = false;
      });
    },
    // 任务组名字典翻译
    jobGroupFormat(row) {
      return this.selectDictLabel(this.jobGroupOptions, row.jobGroup);
    },
    // 状态字典翻译
    statusFormat(row) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 表单重置
    reset() {
      this.form = { status: "0" };
      if (this.$refs.form) {
        this.$refs.form.resetValidation();
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.reset(); // 重置
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange() {
      this.single = this.ids.length !== 1;
      this.multiple = !this.ids.length;
    },
    validate () {
      this.$refs.form.validate()
    },
    // 任务状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.jobName + '"任务吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return changeJobStatus(row.jobId, row.status);
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 表格列点击删除按钮，切换确定删除按钮
    clickHandleRun(item) {
      this.$set(item, 'showConfirmRun', true);
      setTimeout(() => {
        this.$set(item, 'showConfirmRun', false);
      }, 3500);
    },
    /* 立即执行一次 */
    async handleRun(row) {
      this.$store.commit("snackbar/CLOSE_SNACKBAR");
      await runJob(row.jobId, row.jobGroup).then(res => {
        if (res) {
          // 使用全局消息提示
          this.$store.dispatch('snackbar/openSnackbar', {
            msg: '执行成功',
            color: 'success'
          })
        }
      });
    },
    /** 任务详细信息 */
    handleView(row) {
      getJob(row.jobId).then(response => {
        this.form = response.data;
        this.openView = true;
      });
    },
    /** 任务日志列表查询 */
    handleJobLog() {
      this.$router.push("/job/log");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.title = "添加任务";
      this.visible = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const jobId = row.jobId;
      getJob(jobId).then(response => {
        this.form = response.data;
        this.title = "修改任务";
        this.visible = true;
      });
    },
    /** 提交按钮 */
    async submitForm() {
      this.$store.commit("snackbar/CLOSE_SNACKBAR");
      await this.validate();
      if (this.valid) {
        if (this.form.jobId != undefined) {
          await updateJob(this.form).then(res => {
            this.$store.dispatch('snackbar/openSnackbar',{
              msg: '修改成功',
              color: 'success'
            })
            this.getList();
            this.visible = false;
          });
        } else {
          await addJob(this.form).then(res => {
            this.$store.dispatch('snackbar/openSnackbar',{
              msg: '新增成功',
              color: 'success'
            })
            this.getList();
            this.visible = false;
          });
        }
      }
    },
    // 表格列点击删除按钮，切换确定删除按钮
    onClickDelete() {
      this.showConfirmDelete = true;
      setTimeout(() => {
        this.showConfirmDelete = false;
      }, 4000);
    },
    /** 删除按钮操作 */
    async handleDelete() {
      this.$store.commit("snackbar/CLOSE_SNACKBAR");
      const jobIds = this.ids.map(item => item.jobId);
      await delJob(jobIds).then(res => {
        if (res) {
          // 使用全局消息提示
          this.$store.dispatch('snackbar/openSnackbar', {
            msg: '删除成功',
            color: 'success'
          })
          this.getList();
        }
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('schedule/job/export', {
        ...this.queryParams
      }, `job_${new Date().getTime()}.xlsx`)
    },
    updateVisible(value) {
      this.reset();
      this.visible = value;
    },
    getColor (status) {
      if (status == 1) return 'red'
      else return 'green'
    },
  }
};
</script>
